package com.lin.manager.oss.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import com.lin.manager.oss.model.UploadFileData;
import com.lin.manager.oss.storage.StorageEngine;
import com.lin.manager.oss.model.dto.DownloadRespDTO;
import com.lin.manager.oss.model.dto.UploadRespDTO;
import com.lin.manager.oss.service.OssService;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author linjiang
 * @date 2024/7/29
 * @fn 只支持yaml配置的文件服务，如果业务要求数据库支持配置，请关闭配置。
 */
public class OssServiceImpl implements OssService {

    StorageEngine storageEngine;

    public OssServiceImpl(StorageEngine storageEngine) {
        this.storageEngine = storageEngine;
    }

    @Override
    public UploadRespDTO upload(MultipartFile file) throws Exception {
        String originalFilename = file.getOriginalFilename();

        // 构建新文件名称
        String suffix = FileUtil.getSuffix(originalFilename);
        String newFilename = UUID.fastUUID().toString(true) + "." + suffix;
        // 会按照当天的时间戳进行来管理文件
        String path = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/";
        String objectName = path.concat(newFilename);
        // 上传文件
        UploadRespDTO respDTO = storageEngine.put(UploadFileData.builder()
                .objectName(objectName)
                .fileStream(file.getInputStream())
                .build()
        );
        respDTO.setSize(file.getSize());
        respDTO.setContentType(file.getContentType());
        respDTO.setOriginalFileName(originalFilename);
        respDTO.setSuffx(suffix);
        return respDTO;
    }

    @Override
    public DownloadRespDTO download(String objectName) throws Exception {
        DownloadRespDTO downloadFileData = storageEngine.get(objectName);
        return downloadFileData;
    }

}
